package com.wms.service.impl;


import com.wms.bean.Message;
import com.wms.mapper.MessageMapper;
import com.wms.service.EmailService;
import com.wms.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {

    private final MessageMapper messageMapper;
    private final EmailService emailService;

    @Autowired
    public MessageServiceImpl(MessageMapper messageMapper, EmailService emailService) {
        this.messageMapper = messageMapper;
        this.emailService = emailService;
    }

    @Override
    @Transactional
    public boolean sendMessage(Message message) {
        // 设置默认值
        message.setSendTime(LocalDateTime.now());
        message.setReade(false);

        try {
            // 发送邮件
            boolean emailSent = emailService.sendEmail(
                    message.getRecipient(),
                    message.getSubject(),
                    message.getContent()
            );

            // 设置发送状态
            message.setSuccesse(emailSent);

            // 保存到数据库
            messageMapper.insertMessage(message);
            return true;
        } catch (Exception e) {
            // 记录失败状态
            message.setSuccesse(false);
            messageMapper.insertMessage(message);
            return false;
        }
    }

    @Override
    public List<Message> getMessagesByRecipient(String recipient) {
        return messageMapper.getMessagesByRecipient(recipient);
    }

    @Override
    public Message getMessageById(Long id) {
        return messageMapper.getMessageById(id);
    }

    @Override
    public boolean markMessageAsRead(Long id) {
        return messageMapper.updateMessageReadStatus(id, true) > 0;
    }
    @Override
    public List<Message> getMessagesBySenderName(String senderName) {
        return messageMapper.getMessagesBySenderName(senderName);
    }

}